package com.neusoft.controller;

import com.neusoft.feign.CourseFeignClient;
import com.neusoft.po.Course;
import com.neusoft.po.ResponseBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/course")
public class CourseController {
    // 使用 OpenFeign 之前的写法
    // @Autowired
    // private RestTemplate restTemplate;
    // @Autowired
    // private DiscoveryClient discoveryClient;

    // 注入feign接口
    @Qualifier("com.neusoft.feign.CourseFeignClient")
    @Autowired
    private CourseFeignClient cfc;

    @GetMapping("/getCourse/{cno}")
    public ResponseBean<Course> getCourse(@PathVariable("cno") String cno){
        // 这是未启用负载均衡的方法
        // 通过服务器名来获取服务器实例列表
        // List<ServiceInstance> list = discoveryClient.getInstances("provider-server");
        // ServiceInstance instance = list.get(0);
        // String url = "http://"+instance.getHost()+":"+instance.getPort()+"/course/getCourse/"+cno;

        // 这是启用负载均衡后的url写法(也是使用OpenFeign之前的写法)
        // String url = "http://provider-server/course/getCourse/" + cno;
        // ResponseBean rb = restTemplate.getForObject(url, ResponseBean.class);

        ResponseBean<Course> rb = cfc.getCourse(cno);
        return rb;
    }
}







